﻿using AutoMapper;
using CommonType;
using MediatR;
using S_Incident.Domains.EventHandling;
using S_Incident.Infrasturctre.DapperInterface;
using S_Incident.Read.API.Application.Commands;

namespace S_Incident.Read.API.Application.CommandsHanders
{
    public class EventDispositionCommandHanders : IRequestHandler<EventDispositionCommand, PageResule<NodeEventDispositionDto>>
    {
        private readonly IDapperEventDispositionRepository eventDisposition;
        public EventDispositionCommandHanders(IDapperEventDispositionRepository eventDisposition)
        {
            this.eventDisposition = eventDisposition;
        }
        /// <summary>
        /// 显示我的事件信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<PageResule<NodeEventDispositionDto>> Handle(EventDispositionCommand request, CancellationToken cancellationToken)
        {
            var query = $"select a.Id, a.IncidentDescription, a.EventType, a.EventSource, a.ReportingTime, a.Informant, a.AlertStatus, a.NodeId, b.NodeType from EventDisposition as a join Node as b on a.NodeId=b.Id  where a.IsDel=0 and a.EventCategory=0 and 1=1 ";
            if (request.eventLevel != 0)
            {
                query += $" and a.EventLevel={request.eventLevel}";
            }
            var totalCount = await eventDisposition.SelectAsync(request.pageSize, query);
            query += $" ORDER BY a.Id DESC LIMIT {(request.pageIndex - 1) * request.pageSize}, @PageSize;";
            // 使用 AutoMapper 进行类型转换
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap<EventDisposition, NodeEventDispositionDto>()).CreateMapper();
            var result = await eventDisposition.SelectAsync(request.pageSize, query);
            var formManagementProcessDtos = mapper.Map<List<NodeEventDispositionDto>>(result);
            return new PageResule<NodeEventDispositionDto>
            {
                TotalCount = totalCount.Count(),
                PageCount = (int)Math.Ceiling((totalCount.Count() * 1.0) / request.pageSize),
                Data = formManagementProcessDtos
            };
        }
    }
}
